<template>
  <el-dialog title="添加子部门" :visible.sync="dialogVisible" width="50%" @close="handleClose">
    <el-form ref="addFormRef" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width: 80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width: 80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width: 80%" placeholder="请选择">
          <el-option v-for="item in managers" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍">
        <el-input v-model="formData.introduce" style="width: 80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOk">确定</el-button>
        <el-button size="small" @click="handleClose">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getSimpleUserList } from '@/api/user'
import { addDepartment, getDepartments } from '@/api/departments'
export default {
  data() {
    // 部门名称的自定义验证：在一个父级部门下，没有同名的存在
    const checkDepName = (rule, value, callback) => {
      // 找出父id下的所有的子级
      const children = this.depts.filter(item => item.pid === this.formData.pid)
      if (children.length === 0) return callback() // 允许添加
      const isRepeat = children.some(item => item.name === value)
      isRepeat ? callback(new Error('部门名称重复')) : callback()
    }
    // 部门编码的自定义校验：在整个部门下，编码都不能重复
    const checkDepCode = (_, value, callback) => {
      const isRepeat = this.depts.some(item => item.code === value)
      isRepeat ? callback(new Error('部门编码重复')) : callback()
    }
    return {
      // 控制对话框的显示和隐藏
      dialogVisible: false,
      // 表单数据
      formData: {
        name: '',
        code: '',
        introduce: '',
        manager: '',
        pid: ''
      },
      // 表单数据验证规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { validator: checkDepName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { validator: checkDepCode, trigger: 'blur' }
        ],
        manager: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }]
      },
      managers: [], // 管理员数据
      depts: [] // 部门列表数据
    }
  },
  methods: {
    // 打开对话框
    open(pid) {
      this.dialogVisible = true
      // 给pid赋值
      this.formData.pid = pid
      // 获取管理员数据
      this.getManager()
      // 获取部门列表数据
      this.getDepartments()
    },
    // 关闭对话框
    handleClose() {
      this.dialogVisible = false
      // 重置表单（表单数据和表单的验证规则）
      this.$refs.addFormRef.resetFields()
    },
    // 获取管理员数据
    async getManager() {
      this.managers = await getSimpleUserList()
    },
    // 获取部门列表数据
    async getDepartments() {
      const { depts } = await getDepartments()
      this.depts = depts
    },
    // 提交表单
    btnOk() {
      // 校验
      this.$refs.addFormRef.validate(async valid => {
        // 验证失败
        if (!valid) return false
        // 验证成功
        await addDepartment(this.formData)
        // 调用父组件重新获取部门数据
        this.$emit('get-new-deps')
        this.$message.success('添加部门成功')
        this.dialogVisible = false
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
